<template>
	<div class="phoneNav sticky top-0 left-0">
		<ul
			ref="ulTarget"
			class="relative flex items-center overflow-y-auto text-xl text-zinc-600 px-3 duration-1000">
			<li
				class="flex-shrink-0 absolute rounded-lg h-[16px] bg-slate-700 z-[-1] duration-300"
				:style="sliderStyle"></li>
			<li
				class="fixed right-0 shadow-l-white w-8 h-[25px] flex items-center bg-white"
				@click="onPopup">
				<m-svg-icon icon="hamburger"></m-svg-icon>
			</li>
			<li
				v-for="(item, index) in categoryData"
				:key="item.id"
				class="mr-2 flex-shrink-0 mt-1 mb-1 last:mr-10 px-2 py-2"
				:class="{
					'text-zinc-100': $store.getters.currentCategoryIndex === index,
				}"
				:ref="setItemRef"
				@click="onItemClick(index)">
				{{ item.name }}
			</li>
		</ul>
		<m-popup v-model="isShow" @closeMask="isShow = false"
			><m-popup-menu
				:categoryData="categoryData"
				@onItemClick="onItemClick"></m-popup-menu
		></m-popup>
	</div>
</template>

<script setup>
import { ref, onBeforeUpdate, watch, onMounted } from 'vue'
import { useScroll } from '@vueuse/core'
import { useStore } from 'vuex'

defineProps({
	categoryData: {
		type: Array,
		required: true,
	},
})
const sliderStyle = ref({
	width: '12px',
	transform: 'translateX(0px)',
})

/**保存当前选中的元素下标
 * 因为是PC端和移动端的导航栏是一样的，数据共享用VUEX
 */
const store = useStore()
const onItemClick = (index, isClickMenu) => {
	isShow.value = false
	store.commit('category/setCategorysCurrentItem', index)
}

/**当dom发生变化的时候，itemRefs会被不断填满导致重复，需要在onBeforeUpdate数据更新时情况原来的数组
 * 获取填充的所有 item 元素
 *  */
let liArray = []
const setItemRef = (el) => {
	liArray.push(el)
}
onBeforeUpdate(() => {
	liArray = []
})
/**
 * ul偏移的位置
 */
// 获取 ul 元素，以计算偏移位置
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)
const changeSliderPositioin = () => {
	// 获取选中元素的 left、width
	const { left, width } =
		liArray[store.getters.currentCategoryIndex].getBoundingClientRect()

	// 为 sliderStyle 设置属性
	sliderStyle.value = {
		// ul 横向滚动位置 + 当前元素的 left 偏移量-ul本身左侧的paddiing 10px
		transform: `translateX(${ulScrollLeft.value + left - 12 + 'px'})`,
		width: width + 'px',
	}
	// 丝滑滚动导航栏效果
	ulTarget.value.scrollTo({
		left: ulScrollLeft.value + left - window.innerWidth / 2 + width / 2,
		behavior: 'smooth', // 设置滚动行为为平滑滚动
	})
}
onMounted(() => {
	store.commit('category/setCategorysCurrentItem', 0)
	changeSliderPositioin()
})
watch(
	() => store.getters.currentCategoryIndex,
	() => {
		changeSliderPositioin()
	},
)
/**
 * 打开弹窗
 */
const isShow = ref(false)
const onPopup = () => {
	isShow.value = true
}
</script>

<style lang="scss" scoped></style>
